package com.framework.modules.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.framework.common.annotation.Login;
import com.framework.common.annotation.McnLogin;
import com.framework.common.config.SystemConfigName;
import com.framework.common.model.config.ConfigServers;
import com.framework.common.utils.*;
import com.framework.modules.base.entity.*;
import com.framework.modules.base.service.*;
import com.framework.modules.dataview.service.ViewGuildIncomeHistoryInfoService;
import com.framework.modules.dataview.service.ViewGuildMemberListService;
import com.framework.modules.dataview.service.ViewUserInfoLiveService;
import com.framework.modules.guild.entity.GuildEntity;
import com.framework.modules.guild.entity.GuildInviteHistoryEntity;
import com.framework.modules.guild.entity.GuildMembersEntity;
import com.framework.modules.guild.service.GuildInviteHistoryService;
import com.framework.modules.guild.service.GuildMembersService;
import com.framework.modules.guild.service.GuildService;
import com.framework.modules.guild.service.GuildWithdrawHistoryService;
import com.framework.modules.live.entity.LiveHistoryEntity;
import com.framework.modules.live.entity.LiveRoomEntity;
import com.framework.modules.live.entity.LiveViolationLogEntity;
import com.framework.modules.live.service.LiveHistoryService;
import com.framework.modules.live.service.LiveRoomService;
import com.framework.modules.live.service.LiveViolationLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *  
 *
 * @author MIT
 * @email litmiss@gmail.com
 * @date 2020-11-16 09:38:19
 */
@RestController
@RequestMapping("web")
@Api(tags = "PC端网站")
public class WebController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private LiveRoomService liveRoomService;

    @Autowired
    private ViewUserInfoLiveService viewUserInfoLiveService;

    @Autowired
    private ValidateCodeService validateCodeService;

    @Autowired
    private CooperationService cooperationService;

    @Autowired
    private NewsService newsService;

    @Autowired
    private GiftService giftService;

    /**
     * 获取当前用户基本信息
     * 通过当前的 token 识别用户ID，并查询出用户信息
     * 关联表 tb_user , tb_user_info，tb_user_balance
     * @param type 用户信息类型, full 为全部信息,base基础tb_user表信息,info为tb_user_info信息，balance为tb_user_balance信息
     * @return
     */
    @Login
    @CrossOrigin
    @GetMapping("/get_user_info")
    @ApiOperation("获取用户基本信息")
    public R info(String type){
        Long uid=(Long)HttpContextUtils.getHttpServletRequestHeaderValue(HttpContextUtils.USER_KEY);
        //根据token查询用户的基本信息
        Object object=userInfoService.getInfo(uid,type);
        if(object instanceof String){
            return R.error(object.toString());
        }
        return R.ok(object);
    }

    @Login
    @PostMapping("/update_user_nickname")
    @ApiOperation("更新用户昵称")
    public R update_user_nickname(@RequestBody Map<String,String> values){
        Long uid=(Long)HttpContextUtils.getHttpServletRequestHeaderUserid();
        String nickname = values.get("nickname");
        if(StringUtils.isBlank(nickname)){
            return R.error("您的昵称不允许为空，请输入一个昵称 !");
        }
        UserInfoEntity userInfoEntity = new UserInfoEntity();
        userInfoEntity.setNickname(nickname);
        userInfoEntity.setUid(uid.intValue());
        Integer result = userInfoService.updateUserInfo(userInfoEntity);
        return result >0 ? R.ok() : R.error("设置用户昵称失败");
    }

    @GetMapping("/info")
    @ApiOperation("更新用户昵称")
    public R get_info_item(@RequestParam(value = "id",defaultValue = "0") String id){

        NewsEntity entity = newsService.selectById(id);
        if(entity == null){
            return R.error("对不起，没有找到相应内容");
        }
        return R.ok(entity);
    }

    /**
     * 获取直播服务器配置信息
     * 数据库 [ 配置信息  ]  sys_config
     *
     * @return
     */
    @CrossOrigin
    @GetMapping("/get_servers_info")
    @ApiOperation("获取服务器配置信息")
    public R get_servers_info() {
        Map<String, Object> map = new HashMap<>();
        map.put("assets.data.gifts", giftService.selectList(new EntityWrapper<GiftEntity>()));
        map.put("assets.servers", QuickHelper.getConfigValue(SystemConfigName.SERVERS, ConfigServers.class));
        return R.ok("获取成功").put("data", map);
    }

    /**
     * 直播/直播详情
     * 数据库 [ 直播室信息  ]  tb_live_room
     *
     * @return
     */
    //@Login
    @CrossOrigin
    @GetMapping("/get_live_item")
    @ApiOperation("直播详情 ")
    public R getLiveItem(Long uid) {
        if (uid == null) {
            return R.error("请登录");
        }
        Object object = liveRoomService.findLiveInfo(uid.intValue());
        return R.ok(object);
    }

    /**
     * 直播/直播列表
     * 数据库 [ 直播室信息  ]  tb_live_room
     *
     * @param page  页码
     * @param query 用户昵称或友街id
     * @return online_count 在线人数
     * total_seconds 累计直播时间
     * cover_image 直播封面
     * title 直播标题
     * popCount 人气
     * rank 是否推荐 数字越高，推荐级别越高
     * state 直播状态 直播=1,未直播=0,禁播=-1
     */
    //@Login
    @CrossOrigin
    @GetMapping("/get_live_list")
    @ApiOperation("直播列表")
    public R getLiveList(Integer page, String query) {
        Long uid = (Long) HttpContextUtils.getHttpServletRequestHeaderValue("uid");

        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("limit", "12");
        if (StringUtils.isNotBlank(query)) {
            params.put("query", query);
        }
        Object object = viewUserInfoLiveService.queryPage(params);
        return R.ok(object);
    }

    //@Login
    @CrossOrigin
    @GetMapping("/get_zhubo_info")
    @ApiOperation("获取主播信息")
    public R get_zhubo_info(Integer uid) {
        Object object=userInfoService.getInfo(Long.valueOf(uid.toString()),"info");
        if(object instanceof String){
            return R.error(object.toString());
        }
        return R.ok(object);
    }

    /**
     * 获取直播播放地址
     * @param name 该参数为用户的 uid
     * @return
     */
    @GetMapping(value = "get_live_play_url")
    @ApiOperation("直播室播放地址")
    public R getLivePlayUrl(String name) {
        if (StringUtils.isBlank(name)) {
            return R.error("参数错误");
        }
        LiveRoomEntity liveRoomEntity = liveRoomService.selectById(name);
        if (liveRoomEntity != null) {
            if (liveRoomEntity.getState().intValue() < 0) {
                int forbidenTime = liveRoomEntity.getForbiddenEndTime();
                int time = DateUtils.getSecondTimestamp(new Date());
                if (forbidenTime > time) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("forbidden_msg", liveRoomEntity.getForbiddenMsg());
                    map.put("forbiden_end_time", forbidenTime);
                    return R.response(ResponseCode.FORBIDDEN_LIVE).put("data", map);
                } else {
                    LiveRoomEntity liveRoomEntity1 = new LiveRoomEntity();
                    liveRoomEntity1.setUid(Integer.parseInt(name));
                    liveRoomEntity1.setState(0);
                    liveRoomService.updateById(liveRoomEntity1);
                }
            }
        }

        JSONObject obj = QuickHelper.getConfigJSONObject(SystemConfigName.ZHIBO_SDK_CONFIG);
        String active = obj.getString("active");
        JSONObject activeConfig = obj.getJSONObject("templateConfig").getJSONObject(active);

        //推流密钥
        String apikey = activeConfig.getString("ApiKey");

        //播放域名
        String playDomain = activeConfig.getString("PlayDomain");
        Integer expiredSeconds = DateUtils.getSecondTimestamp(new Date()) + 10 * 60 * 1000;
        Map<String,String> map = new HashMap<>();
        map.put("FLV", String.format("http://%s/live/%s.flv", playDomain, name));
        map.put("RTMP", String.format("rtmp://%s/live/%s", playDomain, name));
        map.put("HLS", String.format("http://%s/live/%s.m3u8", playDomain, name));
        map.put("UDP", String.format(String.format("webrtc://%s/live/%s", playDomain, name)));
        return R.ok(map);
    }

    /**
     * 申请合作入驻
     * @param values
     * @return
     */
    @RequestMapping(value = "add_cooperation_apply")
    @ApiOperation("申请合作入驻")
    public R add_cooperation_apply(@RequestBody Map<String,String> values) {

        String mobile = values.get("contact_mobile");
        String code = values.get("validateCode");

        //1.查询是否有获取过的短信
        boolean debug = QuickHelper.getConfigValue(SystemConfigName.DEBUG, Boolean.class);
        Integer smsValidSeconds = QuickHelper.getConfigIntegerValue(SystemConfigName.SMS_CONFIG_VALIDSECONDS);
        ValidateCodeEntity codeEntity = validateCodeService.getLastValidCodeEntry(mobile, smsValidSeconds);
        //检查验证码是否获取 ?
        if (codeEntity == null) {
            return R.error("您还没有获取验证或申请的验证已失效，请重新获取! ");
        }

        if (!codeEntity.getCode().equals(code)) {
            return R.error("手机验证码填写错误，请重新获取! ");
        }

        CooperationEntity entity = new CooperationEntity();
        entity.setCompany(values.get("company"));
        entity.setArea(values.get("area"));
        entity.setContactRealname(values.get("contact_realname"));
        entity.setContactMobile(values.get("contact_mobile"));
        entity.setIp(IPUtils.getIpAddr(SpringContextUtils.getCurrentRequest()));
        entity.setState(0);
        entity.setAdddate(QuickHelper.getNowTimeStampSeconds());
        if (!cooperationService.insert(entity)) {
            return R.error("提交信息错误,请稍后重试");
        }

        return R.ok("提交成功");
    }
}
